package com.fulin.sycnLife;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class QuickEmailToWikiExtractor{
	private ThreadPoolExecutor threadsPool;
	private BlockingQueue<ExchangeEmailShallowDTO> emailQueue;
	public QuickEmailToWikiExtractor(){
		emailQueue = new LinkedBlockingQueue<ExchangeEmailShallowDTO>();
		int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
		threadsPool = new ThreadPoolExecutor(corePoolSize,corePoolSize,101,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(2000));
	}
	
	public void extract() throws InterruptedException{
		System.out.println("开始 " + getExtractorName(0 + ".."));
		long start = System.currentTimeMillis();
		//抽取所有邮件放到队列里
		new ExtractEmailTask().start();
		insertToWiki();
		long end = System.currentTimeMillis();
		double cost = (end - start) / 1000;
		System.out.println("完成 " + getExtractorName(0 + ", 花费时间: " + cost + "秒"));
	}
	
	private String getExtractorName(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 把队列里的文章插入到wiki
	 * @throws InterruptedException 
	 */
	private void insertToWiki() throws InterruptedException{
		//登录Wiki,每间隔一段时间需要登录一次
		while(true){
			//2秒内取不到就退出
			ExchangeEmailShallowDTO email = emailQueue.poll(2, TimeUnit.SECONDS);
			if(email == null){
				break;
			}
			threadsPool.submit(new InsertToWikiTask(email));
		}
	}
	
	protected List<Article> extractEmail(){
		List<ExchangeEmailShallowDTO> allEmails = getEmailService().queryAllEmails();
		if(allEmails == null){
			return null;
		}
		for(ExchangeEmailShallowDTO exchangeEmailShallowDTO : allEmails){
			emailQueue.offer(exchangeEmailShallowDTO);
		}
		return null;
	}
	
	private EmailService getEmailService() {
		return null;
	}

	/**
	 * 抽取邮件任务
	 */
	
	public class ExtractEmailTask extends Thread{
		public void run(){
			extractEmail();
		}
	}
	
	class EmailService{
		public List<ExchangeEmailShallowDTO> queryAllEmails(){
			return null;
		}
	}
	
}
class ExchangeEmailShallowDTO{}

class InsertToWikiTask implements Runnable{

	public InsertToWikiTask(ExchangeEmailShallowDTO email) {
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}}

class Article{}
